package nowCoder;

/**
 *  Given a sorted linked list, delete all duplicates such that each element appear only once.
 For example,
 Given1->1->2, return1->2.
 Given1->1->2->3->3, return1->2->3.
 */


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}
public class Remove_duplicates_from_sorted_list {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null)
            return null;

        ListNode pre = head, cur = head.next;
        while(cur!=null){
            if(cur.val==pre.val){
                ListNode tmp = cur.next;
                removeNode(pre,cur);
                cur = tmp;
            } else{
                pre = cur;
                cur = cur.next;
            }
        }
        return head;
    }
    private void removeNode(ListNode pre, ListNode cur){
        if(cur!=null){
            pre.next = cur.next;
        }
    }

    public static void main(String[] args){
        Remove_duplicates_from_sorted_list remove_duplicates_from_sorted_list = new Remove_duplicates_from_sorted_list();
        ListNode root = new ListNode(1);
       /* root.next = new NNode(1);
        root.next.next = new NNode(3);
        root.next.next.next = new NNode(3);
        root.next.next.next.next = new NNode(4);*/
        ListNode rt = remove_duplicates_from_sorted_list.deleteDuplicates(root);
        while(rt!=null){
            System.out.println(rt.val);
            rt = rt.next;
        }
    }
}
